"""
用户管理模块 - 数据模型
"""
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone
import uuid

from apps.core.models import TimeStampedModel


class User(AbstractUser):
    """
    自定义用户模型
    扩展Django默认用户，支持多角色权限管理
    """
    class Role(models.TextChoices):
        ADMIN = 'admin', '管理员'
        TEACHER = 'teacher', '教师'
        STUDENT = 'student', '学生'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    role = models.CharField(
        max_length=20,
        choices=Role.choices,
        default=Role.STUDENT,
        verbose_name='角色'
    )
    real_name = models.CharField(max_length=50, blank=True, default='', verbose_name='真实姓名')
    phone = models.CharField(max_length=15, blank=True, verbose_name='手机号码')
    avatar = models.ImageField(
        upload_to='avatars/',
        blank=True,
        null=True,
        verbose_name='头像'
    )
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    is_verified = models.BooleanField(default=False, verbose_name='邮箱验证')
    last_login_ip = models.GenericIPAddressField(null=True, blank=True, verbose_name='最后登录IP')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = '用户'
        indexes = [
            models.Index(fields=['role']),
            models.Index(fields=['email']),
            models.Index(fields=['created_at']),
        ]

    def __str__(self):
        return f"{self.get_role_display()} - {self.real_name} ({self.username})"

    @property
    def is_teacher(self):
        """是否为教师"""
        return self.role == self.Role.TEACHER

    @property
    def is_student(self):
        """是否为学生"""
        return self.role == self.Role.STUDENT

    @property
    def is_admin_user(self):
        """是否为管理员"""
        return self.role == self.Role.ADMIN


class StudentProfile(models.Model):
    """
    学生档案
    存储学生特定的详细信息
    """
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='student_profile',
        verbose_name='用户'
    )
    student_id = models.CharField(
        max_length=20,
        unique=True,
        verbose_name='学号'
    )
    class_name = models.CharField(max_length=50, verbose_name='班级')
    grade = models.CharField(max_length=20, verbose_name='年级')
    major = models.CharField(max_length=100, blank=True, verbose_name='专业')
    enrollment_date = models.DateField(verbose_name='入学日期')
    graduation_date = models.DateField(null=True, blank=True, verbose_name='毕业日期')
    gpa = models.DecimalField(
        max_digits=3,
        decimal_places=2,
        null=True,
        blank=True,
        verbose_name='GPA'
    )
    credits = models.IntegerField(default=0, verbose_name='已修学分')

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'student_profiles'
        verbose_name = '学生档案'
        verbose_name_plural = '学生档案'
        indexes = [
            models.Index(fields=['student_id']),
            models.Index(fields=['class_name']),
            models.Index(fields=['grade']),
        ]

    def __str__(self):
        return f"{self.student_id} - {self.user.real_name}"


class TeacherProfile(models.Model):
    """
    教师档案
    存储教师特定的详细信息
    """
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='teacher_profile',
        verbose_name='用户'
    )
    teacher_id = models.CharField(
        max_length=20,
        unique=True,
        verbose_name='工号'
    )
    department = models.CharField(max_length=100, verbose_name='院系')
    title = models.CharField(max_length=50, verbose_name='职称')
    specialization = models.TextField(blank=True, verbose_name='专业方向')
    education = models.CharField(max_length=100, blank=True, verbose_name='学历')
    hire_date = models.DateField(verbose_name='入职日期')
    office = models.CharField(max_length=50, blank=True, verbose_name='办公室')
    research_interests = models.TextField(blank=True, verbose_name='研究方向')
    publications = models.IntegerField(default=0, verbose_name='发表论文数')

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'teacher_profiles'
        verbose_name = '教师档案'
        verbose_name_plural = '教师档案'
        indexes = [
            models.Index(fields=['teacher_id']),
            models.Index(fields=['department']),
            models.Index(fields=['title']),
        ]

    def __str__(self):
        return f"{self.teacher_id} - {self.user.real_name} ({self.title})"


class UserProfile(TimeStampedModel):
    """
    用户配置文件
    存储用户的偏好设置和扩展信息
    """
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='profile',
        verbose_name='用户'
    )
    avatar = models.ImageField(
        upload_to='avatars/',
        blank=True,
        null=True,
        verbose_name='头像'
    )
    bio = models.TextField(
        max_length=500,
        blank=True,
        verbose_name='个人简介'
    )
    learning_progress = models.JSONField(
        default=dict,
        blank=True,
        verbose_name='学习进度'
    )
    preferences = models.JSONField(
        default=dict,
        blank=True,
        verbose_name='用户偏好设置'
    )
    notifications = models.JSONField(
        default=dict,
        blank=True,
        verbose_name='通知设置'
    )

    class Meta:
        db_table = 'user_profiles'
        verbose_name = '用户配置文件'
        verbose_name_plural = '用户配置文件'

    def __str__(self):
        return f"{self.user.username}的配置文件"


class UserSession(models.Model):
    """
    用户会话管理
    用于跟踪用户登录状态和设备信息
    """
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='sessions',
        verbose_name='用户'
    )
    session_key = models.CharField(max_length=40, unique=True, verbose_name='会话键')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(blank=True, verbose_name='用户代理')
    device_info = models.JSONField(default=dict, verbose_name='设备信息')
    location = models.JSONField(default=dict, verbose_name='地理位置')
    is_active = models.BooleanField(default=True, verbose_name='是否活跃')
    last_activity = models.DateTimeField(auto_now=True, verbose_name='最后活动时间')
    login_time = models.DateTimeField(auto_now_add=True, verbose_name='登录时间')
    logout_time = models.DateTimeField(null=True, blank=True, verbose_name='登出时间')

    class Meta:
        db_table = 'user_sessions'
        verbose_name = '用户会话'
        verbose_name_plural = '用户会话'
        indexes = [
            models.Index(fields=['user', 'is_active']),
            models.Index(fields=['session_key']),
            models.Index(fields=['ip_address']),
            models.Index(fields=['last_activity']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.ip_address}"


class UserActivityLog(models.Model):
    """
    用户活动日志
    记录用户的重要操作和行为
    """
    class ActionType(models.TextChoices):
        LOGIN = 'login', '登录'
        LOGOUT = 'logout', '登出'
        CREATE_EXAM = 'create_exam', '创建考试'
        JOIN_EXAM = 'join_exam', '参加考试'
        SUBMIT_EXAM = 'submit_exam', '提交考试'
        CREATE_QUESTION = 'create_question', '创建题目'
        GRADE_EXAM = 'grade_exam', '批改考试'
        AI_GENERATE = 'ai_generate', 'AI生成'

    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='activity_logs',
        verbose_name='用户'
    )
    action_type = models.CharField(
        max_length=50,
        choices=ActionType.choices,
        verbose_name='操作类型'
    )
    description = models.TextField(verbose_name='操作描述')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')
    user_agent = models.TextField(blank=True, verbose_name='用户代理')
    details = models.JSONField(default=dict, verbose_name='详细信息')
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name='时间戳')

    class Meta:
        db_table = 'user_activity_logs'
        verbose_name = '用户活动日志'
        verbose_name_plural = '用户活动日志'
        indexes = [
            models.Index(fields=['user', 'timestamp']),
            models.Index(fields=['action_type']),
            models.Index(fields=['timestamp']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.get_action_type_display()} - {self.timestamp}"


class LoginAttempt(models.Model):
    """
    登录尝试记录
    用于安全监控和防暴力破解
    """
    class Status(models.TextChoices):
        SUCCESS = 'success', '成功'
        FAILED = 'failed', '失败'
        BLOCKED = 'blocked', '被阻止'

    username = models.CharField(max_length=150, verbose_name='用户名')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(blank=True, verbose_name='用户代理')
    status = models.CharField(
        max_length=20,
        choices=Status.choices,
        verbose_name='状态'
    )
    failure_reason = models.CharField(
        max_length=100,
        blank=True,
        verbose_name='失败原因'
    )
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name='时间戳')

    class Meta:
        db_table = 'login_attempts'
        verbose_name = '登录尝试'
        verbose_name_plural = '登录尝试'
        indexes = [
            models.Index(fields=['username', 'timestamp']),
            models.Index(fields=['ip_address', 'timestamp']),
            models.Index(fields=['status']),
        ]

    def __str__(self):
        return f"{self.username} - {self.get_status_display()} - {self.ip_address}"